/*
 SGSortingGameViewController.m
 Date Created: Feburary 24, 2010
 
 Authors: Karanvir Gill <viper1029@gmail.com>
	        Frank Lau <flaua@sfu.ca>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 
 TODO: Better memory management. Need to release items when they are no longer
			 needed.
 */

#import "SGSortingGameViewController.h"
#import "SGPauseViewController.h"
#import "SGRecyclableType.h"
#import "SGBinType.h"
#import "SGBin.h"


@implementation SGSortingGameViewController
@synthesize scoreLabel;
@synthesize sortingGameLevel;


//Initilizes variables that will be used by the game
- (void)viewDidLoad {
	[super viewDidLoad];
	
	self.sortingGameLevel = [[SGSortingGameLevel alloc] initWithLevel:1]; //set level 1 for now
	binsOnScreen = [[NSMutableArray alloc] init]; //will contain all the bins after drawBins is called
	[self drawBins];
	
	score=0;
	numberOfItemsAlreadyDisplayed = 0;
	speedOfItems= [sortingGameLevel speedOfItems];
	totalNumberOfItemsToDisplay= [sortingGameLevel numberOfItemsInLevel];
	//make an array of items that will be used in the current level
	NSArray* avaliableItemsInCurrentLevel = [sortingGameLevel listItemsInLevel];
	
	//make an array of randomly chosen RecyclableType
	//the length of the array is based on totalNumberOfItemsToDisplay 
	arrayOfItemsToDisplay = [[NSMutableArray alloc] init];
	for(int i=0;i<totalNumberOfItemsToDisplay;i++){
		[arrayOfItemsToDisplay addObject:[avaliableItemsInCurrentLevel objectAtIndex:(random() % avaliableItemsInCurrentLevel.count)]];
	}
	//will keep track of which items are on screen
	itemsOnScreen = [[NSMutableArray alloc] init];
}

//Controlled by a timer to create new objects at set time intervals 
- (void)createItem {
	if(numberOfItemsAlreadyDisplayed <totalNumberOfItemsToDisplay){
		SGRecyclableType *itemTypeToCreate = [arrayOfItemsToDisplay objectAtIndex:numberOfItemsAlreadyDisplayed];
		SGRecyclableItem *createdItem = [[SGRecyclableItem alloc] initWithType:itemTypeToCreate xLocation:160 yLocation:-50]; 
		[itemTypeToCreate release];
		[createdItem setUserInteractionEnabled:YES];
		[self.view addSubview:createdItem];
		[itemsOnScreen addObject:createdItem];
		[createdItem release];
		
		numberOfItemsAlreadyDisplayed++;
	}
}

// Loop through all of the items and move them
- (void)moveItems {
	//moves all the items
	for(int i=0;i<itemsOnScreen.count;i++){
		SGRecyclableItem *tempItem = [itemsOnScreen objectAtIndex:i];
		
		if(!tempItem.isBeingDragged) {
			tempItem.center = CGPointMake(tempItem.center.x,tempItem.center.y+speedOfItems.y);
      // Reached the end of the conveyor belt, throw into garbage
			if(tempItem.center.y > 390){//make constant constant
				[tempItem removeFromSuperview];
				[itemsOnScreen removeObjectAtIndex:i];
        i--; // Go over again
			}
		}
	}
	
  // Loop through all of the items and see if they have been moved by the user
  // If they have been moved, remove them and add to score if necessary
	//checks if the item is dropped in the correct bin
	for(int i=0;i<itemsOnScreen.count;i++){
		SGRecyclableItem *tempItem = [itemsOnScreen objectAtIndex:i];
		if(!tempItem.isBeingDragged && tempItem.hasBeenDropped) {
			CGRect tempItemRect = [tempItem frame];
			CGFloat tempItemArea = CGRectGetHeight(tempItemRect)*CGRectGetWidth(tempItemRect);
			//compare the item to all the bins
			for(int k=0;k<binsOnScreen.count;k++){
				SGBin *tempBin = [binsOnScreen objectAtIndex:k];
				CGRect tempBinRect = [tempBin frame];
				//find out how much the item and bin overlap
				CGRect intersectionRect = CGRectIntersection(tempItemRect, tempBinRect);
				CGFloat intersectionArea = CGRectGetHeight(intersectionRect)*CGRectGetWidth(intersectionRect);
				//if the item is more then 40 percent in the bin, then count it as
				//dropped in the bin, otherwise its dropped outside the bin
				if(intersectionArea>tempItemArea/2.5){
					if([tempBin itemAccepted:tempItem]){//check if items is in correct bin
						score += [tempItem depositValue];
						scoreLabel.text = [NSString stringWithFormat:@"%i", score];
					}
				}
			}
      
      // TODO Remove life if not matched to a bin
      
      // All user-moved items should be removed
      [tempItem removeFromSuperview];
      [itemsOnScreen removeObjectAtIndex:i];
      i--; // We just removed the current index, so go over it again..
			NSLog(@"bbbbbbb", itemsOnScreen.count);
		}
	}	
}

-(void)drawBins{
	
	NSArray *arrayWithAllBinTypes = [[NSArray alloc] initWithArray:[SGBinType listBinTypes]];
	
	//setup the bins on the left
	int yLoc = 0;
	for(int i=0;i<4;i++){
		SGBin *tempBin = [[SGBin alloc] initWithType:[arrayWithAllBinTypes objectAtIndex:i] xLocation:2 yLocation:(50+yLoc)];
		[self.view addSubview:tempBin];
		[binsOnScreen addObject:tempBin];
		[tempBin release];
		yLoc = yLoc + 90;
	}
	
	//setup the bins on the right
	yLoc = 0;
	for(int i=4;i<7;i++){
		SGBin *tempBin = [[SGBin alloc] initWithType:[arrayWithAllBinTypes objectAtIndex:i] xLocation:233 yLocation:(100+yLoc)];
		[self.view addSubview:tempBin];
		[binsOnScreen addObject:tempBin];
		[tempBin release];
		yLoc = yLoc + 90;
	}
}

- (void)viewDidAppear:(BOOL)animated {
  // Everything is shown, start the game
  createTimer=[[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(createItem) userInfo:nil repeats:YES] retain];
	moveTimer=[[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(moveItems) userInfo:nil repeats:YES] retain];
}

- (void)viewDidDisappear:(BOOL)animated {
  // View dissapeared, so stop the game
  [createTimer invalidate];
  [moveTimer invalidate];
  [createTimer release];
  [moveTimer release];
}

- (IBAction)pauseGame:(id)sender {
	
	SGPauseViewController *pauseViewController=[[SGPauseViewController alloc] init];
	[[self navigationController] pushViewController:pauseViewController animated:NO];
	[pauseViewController release];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[super dealloc];
}

@end
